<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <title>{$Think.config.admin_title}</title>
    <link rel="stylesheet" href="/static/service/js/layui/css/layui.css">
    <link rel="stylesheet" href="/static/service/css/laykefu.css">
</head>

<body>
    <script src="/static/service/js/layui/layui.js?t={:time()}"></script>
    <script id="detail_user_list" type="text/html">
        <div style="padding: 10px;">
            {{# layui.each(d.service_list, function(index, item){ }}
            <li class="layui-nav-item" style="border-bottom: 1px solid #f7f7f7; background-color: #fff; margin-bottom: 5px;">
                <img src="{{item.user_avatar}}" class="layui-nav-img">{{item.user_name}}
            </li>
            {{# }); }}
        </div>
    </script>
    <script>
        var uid = "{$uinfo['id']}";
        var socket_server = "{$socket}";
        var protocol = location.protocol === 'https:' ? 'wss://' : 'ws://';
        var lockReconnect = false;
        var retryNumber = 0;
        var uinfo = {
            id: 'KF' + uid,
            username: "{$uinfo['user_name']}",
            avatar: "{$uinfo['user_avatar']}",
            role: "{$uinfo['role']}",
            title: "{$uinfo['title']}"
        };

        layui.use(['layer', 'laytpl', 'upload', 'mobile'], function () {
            function getwebsocket(url) {
                socket = new WebSocket(url);
                socket.onopen = function (res) {
                    layer.msg('链接成功', {
                        time: 1000
                    });
                    // 登录
                    socket.send(JSON.stringify({
                        type: "init",
                        uid: uinfo.id,
                        name: uinfo.username,
                        avatar: uinfo.avatar,
                        role: uinfo.role
                    }));
                    layui.$.getJSON("{:url('/service/index/syncChatList')}", {}, (res) => {
                        //清理日志
                        layui.data('layim-mobile', {
                            key: uinfo.id,
                            value: { chatlog: {}, history: {} }
                        });
                        layui.each(res, (i, v) => {
                            layim.setHistory(v);
                        });
                    });
                    //每30秒ping服务器
                    setInterval(function () {
                        if (socket.readyState == 1) {
                            socket.send(JSON.stringify({
                                type: 'ping',
                                data: {
                                    l_user_id: uid
                                }
                            }));
                        } else {
                            reconnect();
                        }
                    }, 30000);
                };
                // 监听消息
                socket.onmessage = function (res) {
                    var data = eval("(" + res.data + ")");
                    switch (data['message_type']) {
                        // 服务端ping客户端
                        case 'ping':
                            socket.send('{"type":"ping"}');
                            break;
                        // 添加用户
                        case 'connect':
                            // addUser(data.data.user_info);
                            // layim.getMessage({
                            //     system: true //系统消息
                            //         ,
                            //     id: data.data.user_info.id //聊天窗口ID
                            //         ,
                            //     type: "group" //聊天窗口类型
                            //         ,
                            //     content: data.data.user_info.name + "上线"
                            // });
                            break;
                        // 移除访客到主面板
                        case 'delUser':
                            layim.removeList({
                                type: 'group',
                                id: data.id
                            });
                            break;
                        // 监测聊天数据
                        case 'chatMessage':
                            // showUserMessage(data.data, data.data.content);
                            break;
                        case 'userSend':
                            // showUserMessage(data.data, data.data.content);
                            obj = {
                                username: data.data.name,
                                avatar: data.data.avatar,
                                id: data.data.id,
                                type: 'group',
                                content: data.data.content
                            }
                            layim.getMessage(obj);
                            break;
                        case 'sendToUser':
                            // showUserMessage(data.data, data.data.content);
                            obj = {
                                username: data.data.name,
                                avatar: data.data.avatar,
                                id: data.data.id,
                                type: 'group',
                                content: data.data.content
                            }
                            layim.getMessage(obj);
                            break;
                        case 'close':
                            // loginOut();
                            break;
                    }
                };

                socket.onclose = function (ev) {
                    if (retryNumber < 3) {
                        retryNumber++;
                        reconnect();
                    } else {
                        layer.msg('无法连接上服务器');
                    }
                }
                return socket;
            }

            function reconnect() {
                if (lockReconnect) return;
                lockReconnect = true;
                //没连接上会一直重连，设置延迟避免请求过多
                setTimeout(function () {
                    layer.msg('已与服务器断开连接,正在尝试重连...', {
                        time: 1000
                    });
                    socket = getwebsocket(protocol + socket_server);
                    lockReconnect = false;
                }, 2000);
            }

            var socket = getwebsocket(protocol + socket_server);
            var layim = layui.mobile.layim,
                layer = layui.layer,
                $ = layui.jquery,
                laytpl = layui.laytpl;

            layim.config({
                //上传图片接口
                uploadImage: {
                    url: '/service/upload/uploadImg',
                    type: 'post'
                }
                //上传文件接口
                ,
                uploadFile: {
                    url: '/service/upload/uploadFile',
                    type: 'post'
                },
                // init: JSON.parse('{$init}'),
                init: {
                    url: "/service/index/init",
                    data: {}
                },
                isNewFriend: false //是否开启“新的朋友”
                ,
                isgroup: true //是否开启“群聊”
                //,chatTitleColor: '#c00' //顶部Bar颜色
                ,
                title: uinfo.title //应用名，默认：我的IM
                ,
                voice: true
                // , chatLog: layui.cache.dir + 'css/modules/layim/html/chatlog.html'
            });

            //查看聊天信息
            layim.on('detail', function (data) {
                $.getJSON('/service/index/userInfo', {
                    id: data.id
                }, (res) => {
                    laytpl(detail_user_list.innerHTML).render(res, function (html) {
                        layim.panel({
                            title: data.name + ' 服务团队',
                            tpl: html
                        });
                    });
                });
            });

            //监听发送消息
            layim.on('sendMessage', function (data) {
                socket.send(JSON.stringify({
                    type: 'sendToUser',
                    data: {
                        from_id: data.mine.id,
                        from_avatar: data.mine.avatar,
                        from_name: data.mine.username,
                        content: data.mine.content,
                        to_id: data.to.id,
                        to_name: data.to.name,
                        user_id: data.to.id,
                    }
                }));
            });
            //监听查看更多记录
            layim.on('chatlog', function (data, ul) {
                let cache = layim.cache();
                let chat_id = layui.data('layim-mobile-user-last_chat_id')[cache.mine.id + data.type + data.id];
                showUserLog(data.type, data.id, chat_id, ul);
            })
            layim.on('chatChange', function (obj) {
                let data = obj.data;
                chatMain = obj.elem.find('.layim-chat-main');
                showUserLog(data.type, data.id, 0, obj.elem.find('ul'));
            });

            function showUserLog(type, id, chat_id, ul) {
                $.getJSON('getUserChatLog/id/' + id, {
                    chat_id: chat_id
                }, (res) => {
                    var cache = layim.cache();
                    let elemChatMain = ['<li class="layim-chat-li{{ d.mine ? " layim-chat-mine" : "" }}">', '<div class="layim-chat-user"><img src="{{ d.avatar }}" alt="{{ d.uid || d.id }}"><cite>', '{{ d.username||"佚名" }}', '</cite></div>', '<div class="layim-chat-text">{{ layui.data.content(d.content||"&nbsp;") }}</div>', '</li>'].join('');
                    let message_length = 0;
                    layui.each(res, function (index, item) {
                        if ('time' == item.type) {
                            ul.prepend('<li class="layim-chat-system"><span>' + layui.data.date(item.time) + '</span></li>');
                        } else {
                            ul.prepend(laytpl(elemChatMain).render(item));
                            message_length++;
                            chat_id = item.chat_id;
                        }
                    });
                    layui.data('layim-mobile-user-last_chat_id', {
                        key: cache.mine.id + type + id,
                        value: chat_id
                    })
                    if (message_length == 10) {
                        if (ul.prev().hasClass('layim-chat-system')) {
                            ul.prev().html('<div class="layim-chat-system"><span layim-event="chatLog">查看更多记录</span></div>')
                        } else {
                            ul.before('<div class="layim-chat-system"><span layim-event="chatLog">查看更多记录</span></div>');
                        }
                    } else {
                        if (ul.prev().hasClass('layim-chat-system')) {
                            ul.prev().html('<div class="layim-chat-system">没有更多记录了</div>')
                        } else {
                            ul.before('<div class="layim-chat-system">没有更多记录了</div>');
                        }
                    }
                    //滚动屏幕
                    if (ul.children('li').eq(res.length - 1).offset()) {
                        chatMain.scrollTop(ul.children('li').eq(res.length - 1).offset().top);
                    } else {
                        chatMain.scrollTop(chatMain[0].scrollHeight);
                    }
                })
            }
        });

        // //模拟"更多"有新动态
        // layim.showNew('More', true);
        // layim.showNew('find', true);
    </script>
</body>

</html>